<script setup lang="ts">
import { ref, watch } from 'vue';
import type { ECOption } from '@/hooks/common/echarts';
import { fetchApiStatistics } from '@/service/api';
import { useBoolean } from '@sa/hooks';
import { useEcharts } from '@/hooks/common/echarts';

defineOptions({
  name: 'ApiStatisticsModal'
});

interface Props {
  apiId: number | null;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', { required: true });

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean();

const dateRange = ref<[number, number]>([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).getTime(),
  new Date().getTime()
]);

const statistics = ref<any>(null);

const { domRef: domRef1, updateOptions: updateOptions1 } = useEcharts(() => ({
  title: { text: '调用统计', left: 'center' },
  tooltip: { trigger: 'item' },
  legend: { orient: 'vertical', left: 'left' },
  series: []
}));

const { domRef: domRef2, updateOptions: updateOptions2 } = useEcharts(() => ({
  title: { text: '响应时间统计', left: 'center' },
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: [] },
  yAxis: { type: 'value', name: '时间(ms)' },
  series: []
}));

watch(visible, () => {
  if (visible.value && props.apiId) {
    loadStatistics();
  }
});

async function loadStatistics() {
  if (!props.apiId) return;

  startLoading();
  try {
    const startDate = new Date(dateRange.value[0]).toISOString().split('T')[0];
    const endDate = new Date(dateRange.value[1]).toISOString().split('T')[0];

    const { data } = await fetchApiStatistics(props.apiId, startDate, endDate);
    if (data) {
      statistics.value = data;
      updateCharts();
    }
  } finally {
    endLoading();
  }
}

function updateCharts() {
  if (!statistics.value) return;

  // 调用统计图表
  updateOptions1(() => ({
    title: { text: '调用统计', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'left' },
    series: [
      {
        name: '调用统计',
        type: 'pie',
        radius: '50%',
        data: [
          { value: statistics.value.successCalls, name: '成功' },
          { value: statistics.value.failedCalls, name: '失败' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }));

  // 响应时间图表
  updateOptions2(() => ({
    title: { text: '响应时间统计', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: ['最小', '平均', '最大']
    },
    yAxis: {
      type: 'value',
      name: '时间(ms)'
    },
    series: [
      {
        name: '响应时间',
        type: 'bar',
        data: [statistics.value.minResponseTime, statistics.value.avgResponseTime, statistics.value.maxResponseTime],
        itemStyle: {
          color: '#5470c6'
        }
      }
    ]
  }));
}

function handleClose() {
  visible.value = false;
}
</script>

<template>
  <NModal v-model:show="visible" preset="card" title="API统计信息" style="width: 1000px">
    <NSpin :show="loading">
      <div class="flex-col gap-16px">
        <NSpace justify="space-between">
          <NDatePicker v-model:value="dateRange" type="daterange" clearable />
          <NButton type="primary" @click="loadStatistics">
            <icon-ic-round-refresh class="mr-4px text-20px" />
            刷新
          </NButton>
        </NSpace>

        <div v-if="statistics">
          <NGrid :cols="4" :x-gap="16" :y-gap="16">
            <NGridItem>
              <NStatistic label="总调用次数" :value="statistics.totalCalls">
                <template #prefix>
                  <icon-ic-round-api class="text-24px text-primary" />
                </template>
              </NStatistic>
            </NGridItem>
            <NGridItem>
              <NStatistic label="成功次数" :value="statistics.successCalls">
                <template #prefix>
                  <icon-ic-round-check-circle class="text-24px text-success" />
                </template>
              </NStatistic>
            </NGridItem>
            <NGridItem>
              <NStatistic label="失败次数" :value="statistics.failedCalls">
                <template #prefix>
                  <icon-ic-round-error class="text-24px text-error" />
                </template>
              </NStatistic>
            </NGridItem>
            <NGridItem>
              <NStatistic label="成功率" :value="statistics.successRate" suffix="%">
                <template #prefix>
                  <icon-ic-round-trending-up class="text-24px text-warning" />
                </template>
              </NStatistic>
            </NGridItem>
          </NGrid>

          <NDivider />

          <NGrid :cols="3" :x-gap="16" :y-gap="16">
            <NGridItem>
              <NStatistic label="今日调用" :value="statistics.todayCalls" />
            </NGridItem>
            <NGridItem>
              <NStatistic label="本周调用" :value="statistics.weekCalls" />
            </NGridItem>
            <NGridItem>
              <NStatistic label="本月调用" :value="statistics.monthCalls" />
            </NGridItem>
          </NGrid>

          <NDivider />

          <NGrid :cols="2" :x-gap="16">
            <NGridItem>
              <div ref="domRef1" class="h-300px"></div>
            </NGridItem>
            <NGridItem>
              <div ref="domRef2" class="h-300px"></div>
            </NGridItem>
          </NGrid>
        </div>
      </div>
    </NSpin>

    <template #footer>
      <NSpace justify="end">
        <NButton @click="handleClose">关闭</NButton>
      </NSpace>
    </template>
  </NModal>
</template>
